package utils

import (
	"net"
	"net/http"
	"time"
)

// source spareIP  target IP
func GetTransport(spareIP, targetIP string) http.RoundTripper {
	return &http.Transport{
		Dial: func(netw, addr string) (net.Conn, error) {
			//本地地址  ipaddr是本地外网IP
			lAddr, err := net.ResolveTCPAddr(netw, spareIP+":0")
			if err != nil {
				return nil, err
			}

			if targetIP != "" {
				_, port, err := net.SplitHostPort(addr)
				if err != nil {
					return nil, err
				}

				addr = net.JoinHostPort(targetIP, port)
			}

			//被请求的地址
			rAddr, err := net.ResolveTCPAddr(netw, addr)
			if err != nil {
				return nil, err
			}
			conn, err := net.DialTCP(netw, lAddr, rAddr)
			if err != nil {
				return nil, err
			}
			deadline := time.Now().Add(30 * time.Second)
			conn.SetDeadline(deadline)
			return conn, nil
		},
	}
}
